package com.service.devimonitor;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.bpms.common.CommonUtil;
import com.bpms.common.JdbcWorker;
import com.bpms.common.VO;
import com.bpms.common.VOList;
import com.bpms.eai.PackTool;
import com.bpms.esb.IService;
import com.zk.atm.forms.AtmpDeviceStatusForm;
import com.zk.atm.forms.AtmpOrgForm;
import com.zk.atm.utils.AccessDBConnection;
import com.zk.atm.utils.ConstantsAtmp;
import com.zk.atm.utils.ConstantsAtmpSql;
import com.zk.atm.utils.JsonUtil;
import com.zk.atm.utils.PrimaryKeyUtil;
import com.zk.atm.utils.StringUtil;
import com.zk.atm.vo.AtmpOrg;
import com.zk.atm.vo.BaseVo;

public class Atmporgserviceimpl extends PackTool implements IService {
    protected Logger logger=Logger.getLogger(Atmporgserviceimpl.class);
    public static void main(String[] args) {
    	Atmporgserviceimpl service=new Atmporgserviceimpl();
    	VO args_vo=new VO();
    	args_vo.setAttr(ConstantsAtmp.ATMP_ORG_LOAD_ALL_DATA_KEY, "1");
    	args_vo.setAttr(ConstantsAtmp.ATMP_CMD_METHOD_KEY_NAME, ConstantsAtmp.ATMP_ORG_GET_ORG_LIST_FOR_COMBOX);
    	service.exec(args_vo);
	}
	@Override
	public VO exec(VO args) {
		VO r=new VO();
		String cmd="";
		try{
			cmd=StringUtil.getPropertyValue(args.getAttr(ConstantsAtmp.ATMP_CMD_METHOD_KEY_NAME));
			if(cmd.equals(ConstantsAtmp.ATMP_ORG_LIST)){
				VO in_clude_list=this.list(args);
				return in_clude_list;
			}else if(cmd.equals(ConstantsAtmp.ATMP_ORG_SAVE)){
				VO ret=this.save(args);
				return ret;
			} else if(cmd.equals(ConstantsAtmp.ATMP_ORG_DEL)){
				VO ret=this.delete(args);
				return ret;
			} else if(cmd.equals(ConstantsAtmp.ATMP_ORG_GET_ORG_LIST_FOR_COMBOX)){
				VO ret=this.get_org_list_for_combox(args);
				return ret;
			}else if(cmd.equals(ConstantsAtmp.ATMP_ORG_GET_DEVICE_TYPE_LIST_FOR_COMBOX)){
				VO ret=this.get_device_type_list_for_combox(args);
				return ret;
			}else if(cmd.equals(ConstantsAtmp.ATMP_ORG_GET_DICT_DEVICE_NAME_LIST_FOR_COMBOX)){
				VO ret=this.get_dict_device_name_list_for_combox(args);
				return ret;//get_dict_device_name_list_for_combox
			}
			CommonUtil.debug("atmporgserviceimpl "+cmd+",success!");
			return r;
		}
		catch(Exception e){
			CommonUtil.debug("atmporgserviceimpl exception",e);
			return null;
		}
	}
	

	public VO list(VO args)   throws Exception{
		VO result_vo=new VO();
		String org_name=StringUtil.getPropertyValue(args.getAttr("org_name"));
		String org_code=StringUtil.getPropertyValue(args.getAttr("org_code"));
		String parent_org_name=StringUtil.getPropertyValue(args.getAttr("parent_org_name"));
		String userid=StringUtil.getPropertyValue(args.getAttr("userid"));
		String device_sql=" select *from atmp_org org  where 1=1 ";
		
		if(!userid.equals("")){
			AtmpDeviceStatusForm form=new AtmpDeviceStatusForm();
			form.setUserid(userid);
			String belong_ids=ConstantsAtmpSql.getBelongOrgIds(form);
			if(!belong_ids.equals("")){
			   device_sql+=" and org.org_id in ("+belong_ids+")";
			}
			//device_sql+=ConstantsAtmpSql.ATMP_PERM_SQL.replaceAll("#userid#", userid);
		}
		if(!org_name.equals("")){
			device_sql+=" and org.org_name like '%"+org_name+"%'";
		}
		if(!org_code.equals("")){
			device_sql+=" and lower(org.org_code) like '%"+org_code+"%'";
		}
		if(!parent_org_name.equals("")){
			device_sql+="  and org.parent_org_name like '%"+parent_org_name+"%'";
		}
		device_sql+=" order by org.org_id,org.org_code,org.parent_org_id ";
		JdbcWorker j=new JdbcWorker();
		VOList volist=j.readAll(new VO(), device_sql);
		if(logger.isDebugEnabled()){
		  //System.out.println("************************size="+volist.listData.size()+",volist="+volist.listData);
		}
		result_vo.setAttr(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_RET, "0");
		result_vo.setAttr(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_MESSAGE, "操作成功!");
		result_vo.setObj(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_VOLIST, volist);
		//System.out.println(JsonUtil.getJsonObjectByBpmVo(result_vo));
		return result_vo;
	}
	
	protected List<AtmpOrg> getAtmpOrgList(VO args) throws Exception{
		List<AtmpOrg> list=new ArrayList();
		AtmpOrgForm form=(AtmpOrgForm) args.getObj(ConstantsAtmp.ATMP_ORG_FORM_ARGS_NAME);
		Connection conn=AccessDBConnection.getConnection();
		try {
			if(conn==null||conn.isClosed()){
				logger.error("获取conn失败!");
				return null;
			}
			String org_name=StringUtil.getPropertyValue(form.getOrg_vo().getOrg_name());
			String parent_org_name=StringUtil.getPropertyValue(form.getOrg_vo().getParent_org_name());
			String device_sql=" select *from atmp_org org  where 1=1 ";

			if(!org_name.equals("")){
				device_sql+=" and org.org_name like '%"+org_name+"%'";
			}
			if(!parent_org_name.equals("")){
				device_sql+="  and org.parent_org_name like '%"+parent_org_name+"%'";
			}
			System.out.println("**********************************sql="+device_sql);
			AtmpStatusCurrentReflect reflect=new AtmpStatusCurrentReflect();
			list=reflect.getListByClassName(device_sql, "com.zk.atm.vo.AtmpOrg");
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			AccessDBConnection.closeConnection(conn);
		}
		return list;
	}
	
	protected Map<String,String> getFilterFieldMap(){
		Map<String,String> map=new HashMap<String,String>();
		map.put("org_id", "org_id");
		map.put("org_name", "org_name");
		map.put("org_code", "org_code");
		map.put("parent_org_id", "parent_org_id");
		map.put("parent_org_name", "parent_org_name");
		map.put("parent_org_code", "parent_org_code");
		return map;
	}
	Map<String,String> filter_field_map=new HashMap<String,String> ();
	public VO save(VO form_vo) throws Exception{
		VO result_vo=new VO();
		
		try {
			String org_id=StringUtil.getPropertyValue(form_vo.getAttr("org_id"));
			String table_name="atmp_org";
			JdbcWorker jdbc=new JdbcWorker();
			//把device里面的值,全部封装到bpmvo中
			AtmpOrg org=new AtmpOrg();
			if(filter_field_map.size()==0){
				filter_field_map=this.getFilterFieldMap();
			}
			VO vo=this.getVO(form_vo,org,filter_field_map);
			String u=StringUtil.getPropertyValue(form_vo.getAttr("u"));
			String primary_column="org_id";
			Date d=new Date();
			String create_date=d.toLocaleString();
			//如果id为空,则表明是新增操作,则获取生成的主键,保存
			if(org_id.equals("")){
				String primary_key=PrimaryKeyUtil.getPrimaryKey(table_name, null);
				vo.setAttr(primary_column, primary_key);
			    vo.voType=table_name;
			    vo.setAttr("create_date",create_date);
			    vo.setAttr("update_date",create_date);
			    vo.setAttr("create_person_uname",u);
			    vo.setAttr("update_person_uname",u);
			    vo.setAttr("is_delete","0");
			    jdbc.insert(vo);
			    System.out.println("新增操作成功!");
			}else{
				VO key_vo=new VO();
				key_vo.setAttr(primary_column, org_id);
				key_vo.keyString=primary_column;
				key_vo.voType=table_name;
				vo.setAttr("update_date",create_date);
				vo.setAttr("update_person_uname",u);
				jdbc.update(vo, key_vo);
				System.out.println("更新操作成功!");
			}
			result_vo.setAttr(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_RET, "0");
			result_vo.setAttr(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_MESSAGE, "操作成功!");
		} catch (Exception e) {
			e.printStackTrace();
			result_vo.setAttr(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_MESSAGE, "操作失败!");
		}
		return result_vo;
	}
	
	protected VO getVO(VO form_vo,BaseVo clazz,Map<String,String> filter_field_map) throws Exception{
		VO vo=new VO();
		if(filter_field_map==null){
			filter_field_map=new HashMap();
		}
		Field[] fields=clazz.getClass().getDeclaredFields();
		for (Field field : fields) {
			String field_name=field.getName();
			//过滤不需要的字段
			if(filter_field_map.get(field_name)==null){
				continue;
			}
			String field_value=StringUtil.getPropertyValue(form_vo.getAttr(field_name));
			System.out.println("field_name="+field_name+",field_value="+field_value);
			vo.setAttr(field_name,field_value);
		}
		return vo;
	}

	public boolean checkOrgReferAtmpDevice(VO form_vo) throws Exception{
		String sql=  "  select count(*) as total from atmp_org ao,atmp_device ad " +
				" where ao.org_id=ad.belong_org_id and ao.org_id=?";
		String id=StringUtil.getPropertyValue(form_vo.getAttr("org_id"));
		if(id.equals("")){
			return false;
		}
		List list=new ArrayList();
		Connection conn=null;
		try {
			conn=AccessDBConnection.getConnection();
			PreparedStatement pst=conn.prepareStatement(sql);
			pst.setString(1, id);
			ResultSet rs=pst.executeQuery();
			while(rs.next()){
				String total=rs.getString("total");
				list.add(total);
			}
			if(list.size()>0){
				Integer number=new Integer(list.get(0).toString());
				return number>0?true:false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			AccessDBConnection.closeConnection(conn);
		}
		return false;
	}

	public VO delete(VO form_vo) throws Exception {
		VO result_vo=new VO();
		try {
			String id=StringUtil.getPropertyValue(form_vo.getAttr("org_id"));
			if(id.equals("")){
				String msg="参数值:org_id为空,不能执行删除操作!";
				System.out.println(msg);
				logger.error("delete:atmp_org:"+msg);
				result_vo.setAttr(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_MESSAGE, msg);
				return result_vo;
			}
			
			boolean is_refer=this.checkOrgReferAtmpDevice(form_vo);
			if(is_refer==true){
				String msg="当前要删除的ID为"+id+"的机构,在设备表中有记录,不能执行删除操作!";
				System.out.println(msg);
				logger.error("delete:atmp_org:"+msg);
				result_vo.setAttr(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_MESSAGE, msg);
				return result_vo;
			}
			
			String exec_sql="  delete from atmp_org org  where 1=1 " +
					" and org.org_id='"+id+"'";
			AtmpOrgForm form=new AtmpOrgForm();
			form.setExec_sql(exec_sql);
			AtmpStatusCurrentReflect.executeSaveOrDelBySql(form);
			result_vo.setAttr(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_RET, "0");
			result_vo.setAttr(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_MESSAGE, "操作成功!");
		} catch (Exception e) {
			e.printStackTrace();
			result_vo.setAttr(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_MESSAGE, "操作失败!");
		}
		return result_vo;
	}
	//机构保存,设备保存,参选机构
	public VO get_org_list_for_combox(VO args)   throws Exception{
		VO result_vo=new VO();
		JdbcWorker j=new JdbcWorker();
		String sql="select o.org_id,o.org_name from atmp_org o  where 1=1 " ;
		String org_id=StringUtil.getPropertyValue(args.getAttr("org_id"));
	    String is_load_all=StringUtil.getPropertyValue(args.getAttr(ConstantsAtmp.ATMP_ORG_LOAD_ALL_DATA_KEY.toUpperCase()));
		//如果是:机构管理,选择父机构,则不加载当前机构;如果是设备管理,则需要加载所有的机构
	    if(is_load_all.equals("")&&!org_id.equals("")){
			sql+="  and o.org_id!='"+org_id+"'";
		}
		sql+=" order by o.parent_org_id desc,o.org_id asc ";
		VOList volist=j.readAll(new VO(), sql);
		result_vo.setAttr(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_RET, "0");
		result_vo.setAttr(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_MESSAGE, "操作成功!");
		result_vo.setObj(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_VOLIST, volist);
		//System.out.println(JsonUtil.getJsonObjectByBpmVo(result_vo));
		return result_vo;
	}
	
	//设备保存,参选设备类型
	public VO get_device_type_list_for_combox(VO args)   throws Exception{
		VO result_vo=new VO();
		JdbcWorker j=new JdbcWorker();
		String sql=" select adt.type_id,adt.type_name from atmp_device_type adt " ;
//		String id=StringUtil.getPropertyValue(args.getAttr("type_id"));
//		if(!id.equals("")){
//			sql+=" and adt.type_id!='"+id+"'";
//		}
		VOList volist=j.readAll(new VO(), sql);
		result_vo.setAttr(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_RET, "0");
		result_vo.setAttr(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_MESSAGE, "操作成功!");
		result_vo.setObj(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_VOLIST, volist);
		return result_vo;
	}
	
	 
	//子设备保存,参选子设备名称
	public VO get_dict_device_name_list_for_combox(VO args)   throws Exception{
			VO result_vo=new VO();
			JdbcWorker j=new JdbcWorker();
			String sql=" select  bd.dictid,bd.dictname from bpm_dict bd where 1=1	" +
					" and bd.is_monitor_column='1' order by  bd.dictid " ;
//			String id=StringUtil.getPropertyValue(args.getAttr("type_id"));
//			if(!id.equals("")){
//				sql+=" and adt.type_id!='"+id+"'";
//			}
			VOList volist=j.readAll(new VO(), sql);
			result_vo.setAttr(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_RET, "0");
			result_vo.setAttr(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_MESSAGE, "操作成功!");
			result_vo.setObj(ConstantsAtmp.ATMP_GATEWAYSERVLET_CONVERT_BPMVO_TO_JSON_VOLIST, volist);
			return result_vo;
		}
}
